package net.piggy.web.controller;

import net.piggy.web.service.SecurityService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class SecurityController {

    @Resource
    private SecurityService securityService;

    @RequestMapping("/")
    public String home() {
        return "redirect:/security";
    }

    @ResponseBody
    @PreAuthorize("@verifyRule.hasAuthority('security:security')")
    @RequestMapping("/security")
    public String security() {
        return "hello security";
    }

    @ResponseBody
    @PostMapping("/login")
    public Map<String,Object> login(String username, String password) {
        Map<String,Object> map = new HashMap<>();
        try {
            String token = securityService.login(username, password);
            map.put("token",token);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return map;
        }
    }

    @ResponseBody
    @PreAuthorize("@verifyRule.hasAuthority('security:test')")
    @RequestMapping("/test")
    public String test() {
        return "hello test";
    }

}
